package controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONArray;
import pojo.User;
import service.LoginService;
import util.RandomValidateCode;

@Controller
public class GetLogin {
	
	@Autowired
	private LoginService loginService;
	
	@RequestMapping("pages/GetLogin.do")
	@ResponseBody
	public ModelAndView GetLoginDo(HttpServletRequest request,String code, String userid, String password,ModelAndView mav) throws Exception {
		//先看验证码
		HttpSession session = request.getSession();
		String target = (String) session.getAttribute("randomcode_key");
		if(!target.equals(code)) {
			mav.setViewName("loginAgain.html");
		}
		int useridInt = Integer.parseInt(userid);
		User result = loginService.selectUser(useridInt,password);
		int role = 0;
		if(result == null) {
			mav.setViewName("loginAgain.html");
		}
		else {
			role = result.getRole();
		}
		//写入userid到session，便于后续处理。
		session.setAttribute("userid", result.getUserid());
		if(role == 1){
			mav.addObject("userid",result.getUserid());
			mav.setViewName("admin.html");
		}
		else if(role == 2) {
			mav.addObject("userid",result.getUserid());
			mav.setViewName("teacher.html");
		}
		else if(role == 3) {
			mav.addObject("userid",result.getUserid());
			mav.setViewName("student.html");
		}
		return mav;
	}
	
	@RequestMapping("pages/GetCheck.do")
	@ResponseBody
	public void checkCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		//设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");
        
        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(request, response);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

	@RequestMapping("pages/GetUser.do")
	@ResponseBody
	public Object getUser() {
		JSONArray json = new JSONArray();
		List<User> list = loginService.selectAll();
		LinkedList<LinkedHashMap<String, Object>>jsonList = new LinkedList<LinkedHashMap<String,Object>>();
		for(User u:list) {
			LinkedHashMap<String, Object> login = new LinkedHashMap<String, Object>();
	        login.put("userID",u.getUserid());
	        login.put("username",u.getUsername());
	        if(u.getRole() == 1) {
	        	login.put("userrole","超级管理员");
	        }
	        else if(u.getRole() == 2) {
	        	login.put("userrole","老师");
	        }
	        else if(u.getRole() == 3) {
	        	login.put("userrole","学生");
	        }
	        jsonList.add(login);
		}
		json = JSONArray.fromObject(jsonList);
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("code", 0);
	    map.put("msg", "查询用户成功。");
	    map.put("count", json.length());
	    map.put("data", jsonList);
	    return map;
	}
	
	@RequestMapping("pages/insertUser.do")
	@ResponseBody
	public Object InsertUser(String username,String password,String role) {
		Map<String, Object> map = new HashMap<String, Object>();
		User u = new User();
		u.setPassword(role);
		u.setRole(Integer.parseInt(password));
		u.setUsername(username);
		int userid = loginService.nextPrimaryKey() + 1;
		u.setUserid(userid);
		int result = loginService.insertUser(u);
		if(result > 0) {
			map.put("success", true);
			map.put("message", "添加成功");
		}
		else {
			map.put("success",false);
			map.put("message", "添加失败");
		}
		return map;
	}
	
}
